{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.metrics import r2_score\n",
    "\n",
    "class LinearRegression:\n",
    "    \n",
    "    def __init__(self):\n",
    "        \"\"\"初始化Linear Regression模型\"\"\"\n",
    "        self.coef_ = None\n",
    "        self.interception_ = None\n",
    "        self._theta = None\n",
    "        \n",
    "    def fit_normal(self, X_train, y_train):\n",
    "        \"\"\"根据训练数据集X_train, y_train训练Linear Regression模型\"\"\"\n",
    "        assert X_train.shape[0] == y_train.shape[0], \"the size of X_train must be equal to the size of y_train\"\n",
    "        \n",
    "        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])\n",
    "        self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)\n",
    "        \n",
    "        self.interception_ = self._theta[0]\n",
    "        self.coef_ = self._theta[1:]\n",
    "        \n",
    "        return self\n",
    "    \n",
    "    def fit_gd(self, X_train, y_train, eta=0.01, n_iters = 1e4):\n",
    "        \"\"\"根据训练数据集X_train, y_train，使用梯度下降法训练Linear Regression模型\"\"\"\n",
    "        assert X_train.shape[0] == y_train.shape[0], \"the size of X_train must be equal to the size of y_train\"\n",
    "        \n",
    "        def J(theta, X_b, y):\n",
    "            try:\n",
    "                return np.sum((y - X_b.dot(theta))**2) / len(X_b)\n",
    "            except:\n",
    "                return float('inf')\n",
    "            \n",
    "        def dJ(theta, X_b, y):\n",
    "            return X_b.T.dot(X_b.dot(theta)-y) * 2. / len(X_b)\n",
    "        \n",
    "        def gradient_descent(X_b, y, initial_theta, eta, n_iters = 1e4, epsilon=1e-8):\n",
    "            theta = initial_theta\n",
    "            i_iter = 0\n",
    "            while i_iter < n_iters:\n",
    "                gradient = dJ(theta, X_b, y)\n",
    "                last_theta = theta\n",
    "                theta = theta - eta * gradient\n",
    "                if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):\n",
    "                    break\n",
    "                i_iter += 1\n",
    "            return theta\n",
    "        \n",
    "        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])\n",
    "        initial_theta = np.zeros(X_b.shape[1])\n",
    "        self._theta = gradient_descent(X_b, y_train, initial_theta, eta)\n",
    "        self.interception_ = self._theta[0]\n",
    "        self.coef_ = self._theta[1:]\n",
    "        return self\n",
    "        \n",
    "    def fit_sgd(self, X_train, y_train, n_iters = 5, t0 = 5, t1 = 50):\n",
    "        \"\"\"根据训练数据集X_train, y_train，使用随机梯度下降法训练Linear Regression模型\"\"\"\n",
    "        assert X_train.shape[0] == y_train.shape[0], \"the size of X_train must be equal to the size of y_train\"\n",
    "\n",
    "        def dJ_sgd(theta, X_b_i, y_i):\n",
    "            return X_b_i.T.dot(X_b_i.dot(theta)-y_i) * 2.\n",
    "\n",
    "        def learning_rate(t, t0, t1):\n",
    "            return t0 / (t + t1)\n",
    "\n",
    "        def sgd(X_b, y, initial_theta, n_iters, t0, t1): # n_iters:对所有的样本看几圈\n",
    "            theta = initial_theta\n",
    "            m = len(X_b)\n",
    "            \n",
    "            i_iter = 0\n",
    "            for i_iter in range (n_iters):\n",
    "                indexes = np.random.permutation(m)\n",
    "                X_b_new = X_b[indexes]\n",
    "                y_new = y[indexes]\n",
    "                for i in range (m):\n",
    "                    gradient = dJ_sgd(theta, X_b_new[i], y_new[i])\n",
    "                    last_theta = theta\n",
    "                    theta = theta - learning_rate(i_iter*m+i, t0, t1) * gradient\n",
    "            return theta\n",
    "        \n",
    "        X_b = np.hstack([np.ones((len(X_train), 1)), X_train])\n",
    "        initial_theta = np.zeros(X_b.shape[1])\n",
    "        self._theta = sgd(X_b, y_train, initial_theta, n_iters, t0, t1)\n",
    "        self.interception_ = self._theta[0]\n",
    "        self.coef_ = self._theta[1:]\n",
    "        return self\n",
    "        \n",
    "    def predict(self, X_predict):\n",
    "        \"\"\"给定待预测数据集X_predict，返回表示X_predict的结果向量\"\"\"\n",
    "        assert self.interception_ is not None and self.coef_ is not None, \"must fit before predict\"\n",
    "        assert X_predict.shape[1] == len(self.coef_), \"the feature number of X_predict must equal to X_train\"\n",
    "        \n",
    "        X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])\n",
    "        return X_b.dot(self._theta)\n",
    "    \n",
    "    def score(self, X_test, y_test):\n",
    "        \"\"\"根据测试数据集X_test, y_test确定当前模型的准确度\"\"\"\n",
    "        \n",
    "        y_predict = self.predict(X_test)\n",
    "        return r2_score(y_test, y_predict)\n",
    "        \n",
    "    def __repr__(self):\n",
    "        return \"LinearRegression()\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = 100000\n",
    "\n",
    "x = np.random.normal(size=m)\n",
    "X = x.reshape(-1, 1)\n",
    "y = 4. * x + 3. + np.random.normal(0, 3, size=m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LinearRegression()"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lin_reg = LinearRegression()\n",
    "lin_reg.fit_sgd(X, y, n_iters=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([3.99610167])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lin_reg.coef_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.999624221389902"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lin_reg.interception_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 真实数据 + sgd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn import datasets\n",
    "\n",
    "boston = datasets.load_boston()\n",
    "X = boston.data\n",
    "y = boston.target\n",
    "\n",
    "X = X[y<50.0]\n",
    "y = y[y<50.0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.8129794056212832"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=666)\n",
    "\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "standScaler = StandardScaler()\n",
    "standScaler.fit(X_train)\n",
    "X_train_standard = standScaler.transform(X_train)\n",
    "X_test_standard = standScaler.transform(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 30.7 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.7763594773981595"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lin_reg = LinearRegression()\n",
    "%time lin_reg.fit_sgd(X_train_standard, y_train)\n",
    "lin_reg.score(X_test_standard, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 271 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.8130771495096732"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lin_reg = LinearRegression()\n",
    "%time lin_reg.fit_sgd(X_train_standard, y_train, n_iters=50)\n",
    "lin_reg.score(X_test_standard, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 462 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.8131205440883096"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "lin_reg = LinearRegression()\n",
    "%time lin_reg.fit_sgd(X_train_standard, y_train, n_iters=100)\n",
    "lin_reg.score(X_test_standard, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 真实数据  + sklearn中的SGD"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 7.52 ms\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.8127351338416419"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.linear_model import SGDRegressor\n",
    "\n",
    "sgd_lin = SGDRegressor()\n",
    "%time sgd_lin.fit(X_train_standard, y_train)\n",
    "sgd_lin.score(X_test_standard, y_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "__init__() got an unexpected keyword argument 'n_iter'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-52-d90399cfef0b>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0msklearn\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlinear_model\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mSGDRegressor\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0msgd_lin\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mSGDRegressor\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mn_iter\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m100\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      4\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrun_line_magic\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'time'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'sgd_lin.fit(X_train_standard, y_train)'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[0msgd_lin\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mscore\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mX_test_standard\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0my_test\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: __init__() got an unexpected keyword argument 'n_iter'"
     ]
    }
   ],
   "source": [
    "from sklearn.linear_model import SGDRegressor\n",
    "\n",
    "sgd_lin = SGDRegressor(n_iter=100)\n",
    "%time sgd_lin.fit(X_train_standard, y_train)\n",
    "sgd_lin.score(X_test_standard, y_test)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "视频中测试了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
